<template>
  <div>
    <div class="title" style="text-align:left">
      <font-awesome-icon icon="newspaper" />&nbsp;商品列表
    </div>
    <div class="block-line">&nbsp;</div>
    <el-table :data="newsData" border style="width: 100%">
      <el-table-column label="商品名称" width="250">
        <template slot-scope="scope">
          <span style="cursor:pointer;" @click="showDetails(scope.row)">{{scope.row.title}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="pubdate" label="发布日期" width="100"></el-table-column>
      <el-table-column prop="price" label="价格" width="100"></el-table-column>
      <el-table-column prop="userid" label="发布者" width="100"></el-table-column>
      <el-table-column prop="amount" label="销售量" width="80"></el-table-column>
      <el-table-column prop="comment" label="评论量" width="80"></el-table-column>
      <el-table-column prop="kill" label="秒杀状态"
        :filters="[{ text: '普通售卖', value: 0 }, { text: '营销秒杀', value: 1 }]"
        :filter-method="filterKillTag" filter-placement="bottom-end" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.kill === 0 ? '' : 'danger'"
            disable-transitions>{{showKillText(scope.row.kill)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="lock" label="状态"
        :filters="[{ text: '已发布', value: 0 }, { text: '未发布', value: 1 }]"
        :filter-method="filterLockTag" filter-placement="bottom-end">
        <template slot-scope="scope">
          <el-tag :type="scope.row.lock === 0 ? 'success' : 'warning'"
            disable-transitions>{{showLockText(scope.row.lock)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400px">
        <template slot-scope="scope">
          <el-button v-if="scope.row.lock == 0" size="mini" type="info" @click="handleLock(scope.row)">
           <font-awesome-icon icon="lock" />&nbsp;锁定</el-button>
          <el-button v-if="scope.row.lock == 1" size="mini" type="warning" @click="handleLock(scope.row)">
           <font-awesome-icon icon="unlock" />&nbsp;解锁</el-button>
          <el-button size="mini" type="primary" @click="handleEdit(scope.row.gid)">
           <font-awesome-icon icon="edit" />&nbsp;修改</el-button>
          <el-button v-if="scope.row.kill == 0" size="mini" type="warning" @click="handleKill(scope.row)">
           <font-awesome-icon icon="fire" />&nbsp;秒杀配置</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">
           <i class="el-icon-delete"></i>&nbsp;删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block-line">&nbsp;</div>
    <div class="text-right"><el-pagination background layout="prev, pager, next" :total="totalPage"
      :current-page.sync="currentPage" @current-change="loadGoodsData"></el-pagination></div>
    <el-dialog :visible.sync="killDialogVisible" width="70%" style="text-align:left" >
      <template slot="title"><div class="dialog-title">
        <font-awesome-icon icon="fire" />&nbsp;商品秒杀配置</div></template>
      <div>
        <el-row>
          <el-col :sm="24">
            <el-form ref="form" :model="form" label-width="120px" :rules="rules"
              label-position="right" size="small" :inline-message="true">
              <el-form-item label="秒杀日期：" :sm="5" prop="dateRange">
                <el-col :sm="16">
                  <el-date-picker
                    v-model="form.dateRange" type="datetimerange"
                    :picker-options="pickerOptions" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" align="right">
                  </el-date-picker>
                </el-col>
              </el-form-item>
              <el-form-item label="秒杀数量：" :sm="3" prop="amount">
                <el-col :sm="16">
                  <el-input v-model="form.amount" placeholder="请输入参与秒杀的商品数量" suffix-icon="el-icon-s-custom"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="秒杀价格：" :sm="3" prop="amount">
                <el-col :sm="16">
                  <el-input v-model="form.price" placeholder="请输入参与秒杀的价格" suffix-icon="el-icon-s-custom"></el-input>
                </el-col>
              </el-form-item>
              <el-form-item>
                <el-col :sm="16">
                  <el-button type="primary" @click="submitForm">创建</el-button>
                  <el-button type="warning" @click="resetForm">重置</el-button>
                </el-col>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <div class="block-line">&nbsp;</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="killDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { Loading } from 'element-ui'
export default {
  data () {
    return {
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      rules: {
        amount: [
          { required: true, message: '请输入秒杀商品数量', trigger: 'blur' },
          { min: 2, max: 50, message: '请配置正确的商品数量', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入秒杀商品价格', trigger: 'blur' }
        ],
        dateRange: [
          { required: true, message: '请设置秒杀周期', trigger: 'blur' }
        ]
      },
      form: {
        gid: 0,
        amount: 0,
        price: 0,
        dateRange: ''
      },
      currentItem: null, // 保存当前配置项
      killDialogVisible: false,
      currentPage: 1,
      totalPage: 200,
      newsData: [],
      content: '',
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: 'video/mp4', // 类型
          src: '' // url地址
        }],
        poster: '', // 封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: false, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        }
      }
    }
  },
  methods: {
    submitForm () { // 【开发】进行远程数据增加
      this.$refs['form'].validate((valid) => {
        if (valid) {
          console.log('秒杀商品数量：' + this.form.amount)
          console.log('秒杀商品价格：' + this.form.price)
          console.log('秒杀开始日期：' + this.$yootk.datetimeConvert(this.form.dateRange[0]))
          console.log('秒杀结束日期：' + this.$yootk.datetimeConvert(this.form.dateRange[1]))
          console.log('秒杀商品ID：' + this.currentItem.gid)
          var killData = { // 创建秒杀数据
            gid: this.currentItem.gid,
            amount: this.form.amount,
            gtitle: this.currentItem.title, // 商品名称
            gprice: this.currentItem.price, // 商品原始价格
            price: this.form.price,
            start: this.$yootk.datetimeConvert(this.form.dateRange[0]),
            end: this.$yootk.datetimeConvert(this.form.dateRange[1])
          }
          this.$back.kill.add(killData).then(res => { // 补充秒杀数据
            console.log(res.data)
          })
          const h = this.$createElement
          this.$notify({
            title: '发布成功',
            message: h('i', {style: 'color: teal'}, '商品秒杀配置完成。')
          })
          this.currentItem.kill = 1 // 配置秒杀
          this.resetForm() // 重置表单
          this.killDialogVisible = false // 隐藏弹出框
          console.log('表单提交成功，等待数据处理！')
        } else {
          console.log('错误，表单验证失败，无法提交！')
          return false
        }
      })
    },
    resetForm () {
      this.$refs['form'].resetFields()
    },
    handleEdit (id) { // 修改新闻信息
      console.log('新闻修改，跳转到修改页，传递新闻id：' + id)
      this.$router.push('/back/admin/goods/goods_edit/' + id).catch(err => err)
    },
    handleKill (item) { // 秒杀处理
      this.currentItem = item
      this.killDialogVisible = true // 显示秒杀配置对话框
    },
    handleLock (item) { // 【开发】修改新闻的锁定状态
      console.log('新闻ID = ' + item.id)
      if (item.lock === 1) {
        item.lock = 0 // 解除锁定状态
        this.$message({type: 'success', message: '新闻已公布'})
      } else {
        item.lock = 1 // 修改锁定状态
        this.$message.warning('新闻已经被锁定，暂时无法浏览')
      }
    },
    handleDelete (item) { // 【开发】新闻数据删除
      this.$confirm('确定要删除该商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.newsData.splice(item, 1)
        this.$message({
          type: 'success',
          message: '商品删除成功!'
        })
      }).catch(() => {})
    },
    filterLockTag (value, row) {
      return row.lock === value
    },
    filterKillTag (value, row) {
      return row.kill === value
    },
    showLockText (val) {
      if (val === 1) {
        return '未发布'
      } else {
        return '已发布'
      }
    },
    showKillText (val) {
      if (val === 1) {
        return '秒杀进行中'
      } else {
        return '普通售卖'
      }
    },
    loadGoodsData () { // 【开发】分页数据加载操作
      let loadingInstance = Loading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
        setTimeout(() => {
          this.$back.goods.goodsList(this, this.currentPage).then(res => { // 加载新闻数据信息
            this.newsData = res.data // 保存新闻列表数据
          })
          loadingInstance.close()
        }, 100)
      })
    }
  },
  mounted () {
    this.loadGoodsData() // 加载用户数据信息
  }
}
</script>
